package com.wocao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wocao.entity.ReqBody;
import com.wocao.entity.ZyOwner;
import com.wocao.mapper.ZyOwnerMapper;
import com.wocao.service.ZyOwnerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wocao.utils.JwtUtils;
import com.wocao.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业主  服务实现类
 */
@Service
public class ZyOwnerServiceImpl extends ServiceImpl<ZyOwnerMapper, ZyOwner> implements ZyOwnerService {

    @Autowired
    private ZyOwnerMapper zyOwnerMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    //分页
    @Override
    public Page<ZyOwner> allPage(Page<ZyOwner> page, ReqBody reqBody) {
        return zyOwnerMapper.allPage(page, reqBody);
    }

    @Override
    public IPage<ZyOwner> getZyOwnerAll(Long current, Long size, Long roomStatus) {
        IPage<ZyOwner> page = zyOwnerMapper.selectZyOwnerAll(new Page<ZyOwner>(current, size), roomStatus);
        return page;
    }

    @Override
    public List<ZyOwner> getOwnerRoomRecordAll(String ownerRealName) {
        List<ZyOwner> zyOwners = zyOwnerMapper.selectzyOwnerRoomRecordAll(ownerRealName);
        return zyOwners;
    }

    @Override
    public ZyOwner getLogin(ZyOwner login) throws Exception {
        ZyOwner owner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>().eq("owner_phone_number", login.getOwnerPhoneNumber()));
        System.err.println(owner);

        if (owner == null) {
            throw new Exception("用户不存在");
        }
        if (!bCryptPasswordEncoder.matches(login.getOwnerPassword(), owner.getOwnerPassword())) {
            throw new Exception("密码错误");
        }
        owner.setToken(JwtUtils.generateToken(login.getOwnerNickname(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES * 12));
        return owner;
    }

    @Override
    public void addRegister(ZyOwner registerOwner) throws Exception {
        ZyOwner owner = zyOwnerMapper.selectOne(new QueryWrapper<ZyOwner>().eq("owner_phone_number", registerOwner.getOwnerPhoneNumber()));
        if (owner != null) {
            throw new Exception("手机号已被注册");
        }
        registerOwner.setOwnerPassword(bCryptPasswordEncoder.encode(registerOwner.getOwnerPassword()));
        zyOwnerMapper.insert(registerOwner);
    }
}




